package dao

import (
	"errors"
	"yundian/internel/app/helper"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/models/comment"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
)

type CommentDao struct {
}

func NewCommentDao() *CommentDao {
	return &CommentDao{}
}

func (dao *CommentDao) SetCommentStatus(m *comment.ThirdComment) *dingo.ErrorWrap {
	db := global.Orm.Model(&m).Where("id", m.Id).Updates(map[string]interface{}{
		"status":         m.Status,
		"reject_message": m.RejectMessage,
	})
	db = global.Orm.Table("places_service_notification").Where("id", m.NotificationId).Update("status", 6)
	if db.Error != nil {
		return dingo.ErrorIf(db.Error)
	}

	if m.Status == 2 {
		db = global.Orm.Table("goods_orders").Where("id", m.GoodsOrderId).Update("status", 2)
		db.Error = dao.GrantOrderCouponComment(m).Err
	}
	return dingo.ErrorIf(db.Error)
}

func (dao *CommentDao) GrantOrderCouponComment(m *comment.ThirdComment) *dingo.ErrorWrap {
	goodsInfo := NewGoodsDao().GetGoodsDetailsByNotificationId(m.NotificationId).Unwrap().(*request.GoodsDetailsRes)
	if goodsInfo.Id == 0 {
		return dingo.ErrorIf(errors.New("order is err"))
	}
	if goodsInfo.Type != 1 {
		return dingo.ErrorIf(nil)
	}

	param := &request.GrantOrderCouponReq{MemberIds: []int{goodsInfo.MemberId}, CouponId: goodsInfo.CouponId}
	if data := NewCouponDao().GrantOrderCoupon(param); data.Err != nil {
		db := global.Orm.Table("places_service_notification").Where("id", m.NotificationId)
		db.Update("status", helper.TypeNumNotificationStatusPending)
		return dingo.ErrorIf(data.Err)
	}

	db := global.Orm.Table("goods_orders").Where("id", m.GoodsOrderId).Update("status", helper.TypeNumGoodsOrderStatusShipped)
	return dingo.ErrorIf(db.Error)
}
